#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <stdio.h>
#include <stdlib.h>
#include "eucl.h"
#define MAXINT	100

enum error{EXITO,ERROR_PARAM,EXCEDE_RANGO,ARCH_NOCREADO};
FILE *archivo;

void help(){

	char help[]=	"Usage:\n"
			"\teucl -h\n"
			"\teucl -V\n"
			"\teucl [options] M N\n"
			"Options:\n"
			"\t-h, --help		Prints usage information.\n"
			"\t-V, --version	Prints version information.\n"
			"\t-o, --output		Path to output file.\n"
			"Examples:\n"
			"\teucl -o - 256 192\n";
	printf("%s",help);
}

void version(){
	printf("eucl version 0.1\n");
}

int main(int argc, char *argv[]){
	unsigned int a;
	unsigned int b;
	unsigned int mcd;
	FILE* file;
	if(argc <= 1){
		help();
	} else {
		if(argc == 2){
			if( (strcmp(argv[1],"-V")==0) || (strcmp(argv[1],"--version")==0) ){
				version();
			} else if( (strcmp(argv[1],"-h")==0) || (strcmp(argv[1],"--help")==0)){
				help();
			} else {
				printf("eucl: invalid option -- '%s'\n",argv[1]);
				printf("Try `eucl --help' for more information.\n");
			}
		} else if(argc == 5){
			if( (strcmp(argv[1],"-o")==0) || (strcmp(argv[1],"--output")==0)){
				a=atoi(argv[3]);
				b=atoi(argv[4]);
				if (a<2 || a>MAXINT || b<2 || b> MAXINT){
					fprintf(stderr,"ERROR: Numero fuera de rango.\n");	
			 		fclose(archivo);
					return EXCEDE_RANGO;
				}
				mcd=eucl(a,b);
				if((strcmp(argv[2],"-")==0)){
					printf("result: %d\n",mcd);
				} else {
					file=fopen(argv[1],"a");
					if(!file){
						fprintf(stderr,"ERROR: Archivo no pudo ser creado\n");
						return ARCH_NOCREADO;
					}
					fprintf(file,"result: %d\n",mcd);
					fclose(file);

				}
			} else {
				printf("eucl: invalid option -- '%s'\n",argv[1]);
				printf("Try `eucl --help' for more information.\n");
			}
		} else {
			printf("eucl: invalid option -- '%s'\n",argv[1]);
			printf("Try `eucl --help' for more information.\n");
		}
	}
 	return EXITO;
}
